package com.tnxst.phexamination.room.converters;

import androidx.room.TypeConverter;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Converters {
    @TypeConverter
    public static Date fromTimestamp(String value) {
        if (value == null) {
            return null;
        }
        DateFormat dateFormat = null;
        if (value.length() > 10) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        }
        Date date = null;
        try {
            if (value != null && value != "")
                date = dateFormat.parse(value);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    @TypeConverter
    public static String dateToTimestamp(Date date) {
        if (date == null) {
            return null;
        }
        DateFormat dateFormat = null;
        if (date.getHours() == 0 && date.getSeconds() == 0 && date.getMinutes() == 0) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        } else {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        if (date == null) {
            return null;
        }
        return dateFormat.format(date);
    }

    @TypeConverter
    public BigDecimal fromLong(Integer value) {
        return value == null ? null : new BigDecimal(value).divide(new BigDecimal(100));
    }

    @TypeConverter
    public Integer toLong(BigDecimal bigDecimal) {
        if (bigDecimal == null) {
            return null;
        } else {
            return bigDecimal.multiply(new BigDecimal(100)).intValue();
        }
    }
}
